package com.kk.netty.nio.demo;

import java.nio.ByteBuffer;

import static com.kk.netty.nio.ByteBufferUtil.debugAll;

public class TestGatheringWrites {
    public static void main(String[] args) {
        ByteBuffer source = ByteBuffer.allocate (32);
        //                     11            24
        source.put ("Hello,world\nI'm zhangsan\nHo".getBytes ( ));
        split (source);

        source.put ("w are you?\nhaha!\n".getBytes ( ));
        split (source);
    }

    private static void split(ByteBuffer source) {
        source.flip ( );
        // source.limit ( ) 缓冲区容量长度
        for (int i = 0; i < source.limit ( ); i++) {
            // 找到一条完整信息
            if (source.get (i) == '\n') {
                System.out.println (i);
                // 计算每个 \n 词组的长度（换行符号 +1 - 游标起始位置）
                int length = i + 1 - source.position ( );
                // 将这条完整信息存入新的 bytebuffer
                ByteBuffer target = ByteBuffer.allocate (length);
                // 从 source 读，向 target 写
                for (int j = 0; j < length; j++) {
                    target.put (source.get ());
                }
                debugAll (target);
            }
        }
        // 未读的往前移动
        source.compact ( );
    }
}
